/* 封装文件I/O接口 */
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <error.h>
#include <unistd.h>
#include <string.h>

using namespace std;
#define BUFFERSIZE 256

/* 打开 关闭 读取 写入信息*/

/* 文件系统 */
class MyFile
{
public:
    /* 有参构造 */
    MyFile(const char * pathname, int flags, int mode)
    {
        m_pathname = pathname;
        m_flags = flags;
        m_mode = mode;

    }
    MyFile(const string & pathname, int flags, int mode)
    {
        m_pathname = pathname.c_str();
        m_flags = flags;
        m_mode = mode;
    }

public:
    /* 获取文件属性 */
    void GetStat()
    {
        struct stat statbuf;
        stat(m_pathname.c_str(), &statbuf);
        cout << "size  =" << statbuf.st_size << endl;
    }

    /* 打开文件，返回文件描述符 */
    int myOpen()
    {
        m_fd = open(m_pathname.c_str(), m_flags, m_mode);
        if(m_fd == -1)
        {
            perror("file open error:");
        }
        return m_fd;
    }

    /* 关闭文件 */
    void myClose()
    {
        close(m_fd);
    }

    int myWrite()
    {
        cout << "请输入要写入文件的内容：" ;
        string buf;
        cin >> buf;
        int wirteBytes = write(m_fd, buf.c_str(), buf.size());
        cout << "wirteBytes = " << wirteBytes << endl;
        return wirteBytes;
    }

    int myRead()
    {
        lseek(m_fd, 0, SEEK_SET);
        char buffer[BUFFERSIZE] = {0};
        int readBytes = read(m_fd, buffer, BUFFERSIZE);
        
        cout << "readBytes =  " << readBytes  << " buffer:" << buffer << endl;
        return readBytes;
    }


private:
    int m_fd;
    int m_flags;
    int m_mode;
    string m_pathname;
    //string m_buf;
    //char * m_buffer;
};

int main()
{
    MyFile file("./test3.txt", O_CREAT | O_RDWR | O_TRUNC, 0644);
    
    file.myOpen();
    file.myWrite();
    file.myRead();
    file.GetStat();
    file.myClose();

    return 0;
}

